// This source is subject to the Microsoft Public License.
// See http://www.microsoft.com/resources/sharedsource/licensingbasics/sharedsourcelicenses.mspx.
// All other rights reserved.

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Configuration;
using System.Diagnostics;
using System.IO;
using System.Windows.Forms;
using System.Data;
using System.Xml;

using Infragistics.Win.UltraWinTree;

namespace QuoteAdvantageEditor
{
	/// <summary>
	/// Main application window for the QuoteAdvantage Editor
	/// </summary>
	public class MainWindow : System.Windows.Forms.Form
	{
      protected bool bNeedSave = false;
      protected bool bWorking = false;  // Used to protect against rapid clicking
      private AuthoringEngine   eng = new AuthoringEngine(); 
      private XmlNode  nodeCategoryListRoot = null; 
      private Settings objSettings = new Settings();
      private string strCategoryListFileName = "";
      private System.Windows.Forms.MenuItem menuItem2;
      private System.Windows.Forms.MenuItem menuItem7;
      private System.Windows.Forms.MenuItem mnuFileExit;
      private System.Windows.Forms.MenuItem mnuFileNew;
      private System.Windows.Forms.MenuItem mnuFileOpen;
      private System.Windows.Forms.MenuItem mnuHelpAbout;
      private System.Windows.Forms.MainMenu mnuMainMenu;
      private System.Windows.Forms.Button btnAddCategory;
      private System.Windows.Forms.Button btnAddProduct;
      private System.Windows.Forms.Label label1;
      private System.Windows.Forms.ColumnHeader colName;
      private System.Windows.Forms.ColumnHeader colProductId;
      private System.Windows.Forms.Splitter splitter1;
      private System.Windows.Forms.ImageList imgTreeList;
      private System.Windows.Forms.Label lblAvailableItemsInCategory;
      private System.Windows.Forms.MenuItem mnuFileSettings;
      private System.Windows.Forms.Panel pnlLeft;
      private System.Windows.Forms.Panel pnlRight;
      private System.Windows.Forms.ContextMenu mnuTreeList;
      private System.Windows.Forms.MenuItem menuItem11;
      private System.Windows.Forms.ContextMenu mnuProductList;
      private System.Windows.Forms.MenuItem menuItem15;
      private System.Windows.Forms.MenuItem menuItem16;
      private System.Windows.Forms.MenuItem mnuContextAddProduct;
      private Infragistics.Win.UltraWinTree.UltraTree ctlCategoryList;
      private System.Windows.Forms.ListView ctlProductList;
      private System.Windows.Forms.MenuItem mnuContextModifyProduct;
      private System.Windows.Forms.MenuItem mnuContextChildProducts;
      private System.Windows.Forms.MenuItem mnuModifyCategory;
      private System.Windows.Forms.MenuItem mnuAddCategory;
      private System.Windows.Forms.MenuItem mnuFileSave;
      private System.Windows.Forms.MenuItem mnuMoveUp;
      private System.Windows.Forms.MenuItem mnuMoveDown;
      private System.Windows.Forms.MenuItem mnuMoveLeft;
      private System.Windows.Forms.MenuItem mnuMoveRight;
      private System.Windows.Forms.MenuItem mnuEditCategoryAdd;
      private System.Windows.Forms.MenuItem menuItem18;
      private System.Windows.Forms.MenuItem menuItem6;
      private System.Windows.Forms.MenuItem mnuMoveDown2;
      private System.Windows.Forms.MenuItem mnuMoveUp2;
      private System.Windows.Forms.MenuItem mnuMoveLeft2;
      private System.Windows.Forms.MenuItem mnuMoveRight2;
      private System.Windows.Forms.MenuItem mnuEditCategoryModify;
      private System.Windows.Forms.MenuItem mnuRemoveCategory;
      private System.Windows.Forms.MenuItem mnuEditCategoryRemove;
      private System.Windows.Forms.MenuItem mnuEditCategory;
      private System.Windows.Forms.MenuItem mnuEditParentProduct;
      private System.Windows.Forms.MenuItem mnuEditParentProductAdd;
      private System.Windows.Forms.MenuItem mnuEditParentProductModify;
      private System.Windows.Forms.MenuItem mnuEditParentProductRemove;
      private System.Windows.Forms.MenuItem mnuEditParentProductChildProducts;
      private System.Windows.Forms.MenuItem mnuContextRemoveProduct;
      private System.Windows.Forms.MenuItem mnuHelpTopics;
      private System.Windows.Forms.MenuItem menuItem5;
      private System.Windows.Forms.MenuItem mnuFile;
      private System.Windows.Forms.MenuItem mnuEdit;
      private System.Windows.Forms.MenuItem mnuEditParentProductLinkedItems;
      private System.Windows.Forms.MenuItem mnuContextLinkedItems;
      private System.Windows.Forms.MenuItem menuItem1;
      private System.Windows.Forms.MenuItem mnuMoveProductUp;
      private System.Windows.Forms.MenuItem mnuMoveProductDown;
      private System.ComponentModel.IContainer components;

		public MainWindow()
		{
			//
			// Required for Windows Form Designer support
			//
			InitializeComponent();

			//
			// TODO: Add any constructor code after InitializeComponent call
			//
		}

		/// <summary>
		/// Clean up any resources being used.
		/// </summary>
		protected override void Dispose( bool disposing )
		{
			if( disposing )
			{
				if (components != null) 
				{
					components.Dispose();
				}
			}
			base.Dispose( disposing );
		}

		#region Windows Form Designer generated code
		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
         this.components = new System.ComponentModel.Container();
         System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(MainWindow));
         Infragistics.Win.UltraWinTree.UltraTreeColumnSet ultraTreeColumnSet1 = new Infragistics.Win.UltraWinTree.UltraTreeColumnSet();
         this.mnuMainMenu = new System.Windows.Forms.MainMenu();
         this.mnuFile = new System.Windows.Forms.MenuItem();
         this.mnuFileNew = new System.Windows.Forms.MenuItem();
         this.mnuFileOpen = new System.Windows.Forms.MenuItem();
         this.mnuFileSave = new System.Windows.Forms.MenuItem();
         this.mnuFileSettings = new System.Windows.Forms.MenuItem();
         this.menuItem7 = new System.Windows.Forms.MenuItem();
         this.mnuFileExit = new System.Windows.Forms.MenuItem();
         this.mnuEdit = new System.Windows.Forms.MenuItem();
         this.mnuEditCategory = new System.Windows.Forms.MenuItem();
         this.mnuEditCategoryAdd = new System.Windows.Forms.MenuItem();
         this.mnuEditCategoryModify = new System.Windows.Forms.MenuItem();
         this.mnuEditCategoryRemove = new System.Windows.Forms.MenuItem();
         this.menuItem18 = new System.Windows.Forms.MenuItem();
         this.mnuMoveUp2 = new System.Windows.Forms.MenuItem();
         this.mnuMoveDown2 = new System.Windows.Forms.MenuItem();
         this.mnuMoveLeft2 = new System.Windows.Forms.MenuItem();
         this.mnuMoveRight2 = new System.Windows.Forms.MenuItem();
         this.mnuEditParentProduct = new System.Windows.Forms.MenuItem();
         this.mnuEditParentProductAdd = new System.Windows.Forms.MenuItem();
         this.mnuEditParentProductModify = new System.Windows.Forms.MenuItem();
         this.mnuEditParentProductRemove = new System.Windows.Forms.MenuItem();
         this.menuItem6 = new System.Windows.Forms.MenuItem();
         this.mnuEditParentProductLinkedItems = new System.Windows.Forms.MenuItem();
         this.mnuEditParentProductChildProducts = new System.Windows.Forms.MenuItem();
         this.menuItem2 = new System.Windows.Forms.MenuItem();
         this.mnuHelpTopics = new System.Windows.Forms.MenuItem();
         this.menuItem5 = new System.Windows.Forms.MenuItem();
         this.mnuHelpAbout = new System.Windows.Forms.MenuItem();
         this.ctlProductList = new System.Windows.Forms.ListView();
         this.colName = new System.Windows.Forms.ColumnHeader();
         this.colProductId = new System.Windows.Forms.ColumnHeader();
         this.mnuProductList = new System.Windows.Forms.ContextMenu();
         this.mnuContextChildProducts = new System.Windows.Forms.MenuItem();
         this.mnuContextLinkedItems = new System.Windows.Forms.MenuItem();
         this.mnuContextModifyProduct = new System.Windows.Forms.MenuItem();
         this.menuItem16 = new System.Windows.Forms.MenuItem();
         this.mnuContextAddProduct = new System.Windows.Forms.MenuItem();
         this.mnuContextRemoveProduct = new System.Windows.Forms.MenuItem();
         this.imgTreeList = new System.Windows.Forms.ImageList(this.components);
         this.btnAddCategory = new System.Windows.Forms.Button();
         this.btnAddProduct = new System.Windows.Forms.Button();
         this.label1 = new System.Windows.Forms.Label();
         this.lblAvailableItemsInCategory = new System.Windows.Forms.Label();
         this.pnlLeft = new System.Windows.Forms.Panel();
         this.ctlCategoryList = new Infragistics.Win.UltraWinTree.UltraTree();
         this.mnuTreeList = new System.Windows.Forms.ContextMenu();
         this.mnuModifyCategory = new System.Windows.Forms.MenuItem();
         this.menuItem15 = new System.Windows.Forms.MenuItem();
         this.mnuAddCategory = new System.Windows.Forms.MenuItem();
         this.mnuRemoveCategory = new System.Windows.Forms.MenuItem();
         this.menuItem11 = new System.Windows.Forms.MenuItem();
         this.mnuMoveUp = new System.Windows.Forms.MenuItem();
         this.mnuMoveDown = new System.Windows.Forms.MenuItem();
         this.mnuMoveLeft = new System.Windows.Forms.MenuItem();
         this.mnuMoveRight = new System.Windows.Forms.MenuItem();
         this.pnlRight = new System.Windows.Forms.Panel();
         this.splitter1 = new System.Windows.Forms.Splitter();
         this.menuItem1 = new System.Windows.Forms.MenuItem();
         this.mnuMoveProductUp = new System.Windows.Forms.MenuItem();
         this.mnuMoveProductDown = new System.Windows.Forms.MenuItem();
         this.pnlLeft.SuspendLayout();
         ((System.ComponentModel.ISupportInitialize)(this.ctlCategoryList)).BeginInit();
         this.pnlRight.SuspendLayout();
         this.SuspendLayout();
         // 
         // mnuMainMenu
         // 
         this.mnuMainMenu.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
                                                                                    this.mnuFile,
                                                                                    this.mnuEdit,
                                                                                    this.menuItem2});
         // 
         // mnuFile
         // 
         this.mnuFile.Index = 0;
         this.mnuFile.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
                                                                                this.mnuFileNew,
                                                                                this.mnuFileOpen,
                                                                                this.mnuFileSave,
                                                                                this.mnuFileSettings,
                                                                                this.menuItem7,
                                                                                this.mnuFileExit});
         this.mnuFile.Text = "&File";
         // 
         // mnuFileNew
         // 
         this.mnuFileNew.Index = 0;
         this.mnuFileNew.Text = "New...";
         this.mnuFileNew.Click += new System.EventHandler(this.mnuFileNew_Click);
         // 
         // mnuFileOpen
         // 
         this.mnuFileOpen.Index = 1;
         this.mnuFileOpen.Text = "Open...";
         this.mnuFileOpen.Click += new System.EventHandler(this.mnuFileOpen_Click);
         // 
         // mnuFileSave
         // 
         this.mnuFileSave.Index = 2;
         this.mnuFileSave.Text = "Save";
         this.mnuFileSave.Click += new System.EventHandler(this.mnuFileSave_Click);
         // 
         // mnuFileSettings
         // 
         this.mnuFileSettings.Index = 3;
         this.mnuFileSettings.Text = "Settings...";
         this.mnuFileSettings.Click += new System.EventHandler(this.mnuFileSettings_Click);
         // 
         // menuItem7
         // 
         this.menuItem7.Index = 4;
         this.menuItem7.Text = "-";
         // 
         // mnuFileExit
         // 
         this.mnuFileExit.Index = 5;
         this.mnuFileExit.Text = "Exit";
         this.mnuFileExit.Click += new System.EventHandler(this.mnuFileExit_Click);
         // 
         // mnuEdit
         // 
         this.mnuEdit.Index = 1;
         this.mnuEdit.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
                                                                                this.mnuEditCategory,
                                                                                this.mnuEditParentProduct});
         this.mnuEdit.Text = "&Edit";
         // 
         // mnuEditCategory
         // 
         this.mnuEditCategory.Index = 0;
         this.mnuEditCategory.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
                                                                                        this.mnuEditCategoryAdd,
                                                                                        this.mnuEditCategoryModify,
                                                                                        this.mnuEditCategoryRemove,
                                                                                        this.menuItem18,
                                                                                        this.mnuMoveUp2,
                                                                                        this.mnuMoveDown2,
                                                                                        this.mnuMoveLeft2,
                                                                                        this.mnuMoveRight2});
         this.mnuEditCategory.Text = "Category";
         this.mnuEditCategory.Popup += new System.EventHandler(this.mnuEditCategory_Popup);
         // 
         // mnuEditCategoryAdd
         // 
         this.mnuEditCategoryAdd.Index = 0;
         this.mnuEditCategoryAdd.Text = "Add";
         this.mnuEditCategoryAdd.Click += new System.EventHandler(this.mnuEditCategoryAdd_Click);
         // 
         // mnuEditCategoryModify
         // 
         this.mnuEditCategoryModify.Index = 1;
         this.mnuEditCategoryModify.Text = "Modify...";
         this.mnuEditCategoryModify.Click += new System.EventHandler(this.mnuEditCategoryModify_Click);
         // 
         // mnuEditCategoryRemove
         // 
         this.mnuEditCategoryRemove.Index = 2;
         this.mnuEditCategoryRemove.Text = "Remove";
         // 
         // menuItem18
         // 
         this.menuItem18.Index = 3;
         this.menuItem18.Text = "-";
         // 
         // mnuMoveUp2
         // 
         this.mnuMoveUp2.Index = 4;
         this.mnuMoveUp2.Text = "Move Up";
         // 
         // mnuMoveDown2
         // 
         this.mnuMoveDown2.Index = 5;
         this.mnuMoveDown2.Text = "Move Down";
         // 
         // mnuMoveLeft2
         // 
         this.mnuMoveLeft2.Index = 6;
         this.mnuMoveLeft2.Text = "Move Left";
         // 
         // mnuMoveRight2
         // 
         this.mnuMoveRight2.Index = 7;
         this.mnuMoveRight2.Text = "Move Right";
         // 
         // mnuEditParentProduct
         // 
         this.mnuEditParentProduct.Index = 1;
         this.mnuEditParentProduct.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
                                                                                             this.mnuEditParentProductAdd,
                                                                                             this.mnuEditParentProductModify,
                                                                                             this.mnuEditParentProductRemove,
                                                                                             this.menuItem6,
                                                                                             this.mnuEditParentProductLinkedItems,
                                                                                             this.mnuEditParentProductChildProducts});
         this.mnuEditParentProduct.Text = "Parent Product";
         this.mnuEditParentProduct.Popup += new System.EventHandler(this.mnuEditParentProduct_Popup);
         // 
         // mnuEditParentProductAdd
         // 
         this.mnuEditParentProductAdd.Index = 0;
         this.mnuEditParentProductAdd.Text = "Add";
         this.mnuEditParentProductAdd.Click += new System.EventHandler(this.mnuEditParentProductAdd_Click);
         // 
         // mnuEditParentProductModify
         // 
         this.mnuEditParentProductModify.Index = 1;
         this.mnuEditParentProductModify.Text = "Modify...";
         this.mnuEditParentProductModify.Click += new System.EventHandler(this.mnuEditParentProductModify_Click);
         // 
         // mnuEditParentProductRemove
         // 
         this.mnuEditParentProductRemove.Index = 2;
         this.mnuEditParentProductRemove.Text = "Remove";
         this.mnuEditParentProductRemove.Click += new System.EventHandler(this.mnuEditParentProductRemove_Click);
         // 
         // menuItem6
         // 
         this.menuItem6.Index = 3;
         this.menuItem6.Text = "-";
         // 
         // mnuEditParentProductLinkedItems
         // 
         this.mnuEditParentProductLinkedItems.Index = 4;
         this.mnuEditParentProductLinkedItems.Text = "Linked Items...";
         this.mnuEditParentProductLinkedItems.Click += new System.EventHandler(this.mnuEditParentProductLinkedItems_Click);
         // 
         // mnuEditParentProductChildProducts
         // 
         this.mnuEditParentProductChildProducts.Index = 5;
         this.mnuEditParentProductChildProducts.Text = "Child Products...";
         this.mnuEditParentProductChildProducts.Click += new System.EventHandler(this.mnuEditParentProductChildProducts_Click);
         // 
         // menuItem2
         // 
         this.menuItem2.Index = 2;
         this.menuItem2.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
                                                                                  this.mnuHelpTopics,
                                                                                  this.menuItem5,
                                                                                  this.mnuHelpAbout});
         this.menuItem2.Text = "&Help";
         // 
         // mnuHelpTopics
         // 
         this.mnuHelpTopics.Index = 0;
         this.mnuHelpTopics.Text = "Help Topics";
         this.mnuHelpTopics.Click += new System.EventHandler(this.mnuHelpTopics_Click);
         // 
         // menuItem5
         // 
         this.menuItem5.Index = 1;
         this.menuItem5.Text = "-";
         // 
         // mnuHelpAbout
         // 
         this.mnuHelpAbout.Index = 2;
         this.mnuHelpAbout.Text = "About QuoteAdvantage Editor...";
         this.mnuHelpAbout.Click += new System.EventHandler(this.mnuHelpAbout_Click);
         // 
         // ctlProductList
         // 
         this.ctlProductList.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) 
            | System.Windows.Forms.AnchorStyles.Left) 
            | System.Windows.Forms.AnchorStyles.Right)));
         this.ctlProductList.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
                                                                                         this.colName,
                                                                                         this.colProductId});
         this.ctlProductList.ContextMenu = this.mnuProductList;
         this.ctlProductList.FullRowSelect = true;
         this.ctlProductList.Location = new System.Drawing.Point(8, 24);
         this.ctlProductList.MultiSelect = false;
         this.ctlProductList.Name = "ctlProductList";
         this.ctlProductList.Size = new System.Drawing.Size(400, 418);
         this.ctlProductList.SmallImageList = this.imgTreeList;
         this.ctlProductList.TabIndex = 1;
         this.ctlProductList.View = System.Windows.Forms.View.Details;
         this.ctlProductList.DoubleClick += new System.EventHandler(this.ctlProductList_DoubleClick);
         // 
         // colName
         // 
         this.colName.Text = "Name";
         this.colName.Width = 253;
         // 
         // colProductId
         // 
         this.colProductId.Text = "Product ID";
         this.colProductId.Width = 108;
         // 
         // mnuProductList
         // 
         this.mnuProductList.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
                                                                                       this.mnuContextChildProducts,
                                                                                       this.mnuContextLinkedItems,
                                                                                       this.mnuContextModifyProduct,
                                                                                       this.menuItem16,
                                                                                       this.mnuContextAddProduct,
                                                                                       this.mnuContextRemoveProduct,
                                                                                       this.menuItem1,
                                                                                       this.mnuMoveProductUp,
                                                                                       this.mnuMoveProductDown});
         this.mnuProductList.Popup += new System.EventHandler(this.mnuProductList_Popup);
         // 
         // mnuContextChildProducts
         // 
         this.mnuContextChildProducts.Index = 0;
         this.mnuContextChildProducts.Text = "Child Products...";
         this.mnuContextChildProducts.Click += new System.EventHandler(this.mnuContextChildProducts_Click);
         // 
         // mnuContextLinkedItems
         // 
         this.mnuContextLinkedItems.Index = 1;
         this.mnuContextLinkedItems.Text = "Linked Items...";
         this.mnuContextLinkedItems.Click += new System.EventHandler(this.mnuLinkedItems_Click);
         // 
         // mnuContextModifyProduct
         // 
         this.mnuContextModifyProduct.Index = 2;
         this.mnuContextModifyProduct.Text = "Modify...";
         this.mnuContextModifyProduct.Click += new System.EventHandler(this.mnuContextModifyProduct_Click);
         // 
         // menuItem16
         // 
         this.menuItem16.Index = 3;
         this.menuItem16.Text = "-";
         // 
         // mnuContextAddProduct
         // 
         this.mnuContextAddProduct.Index = 4;
         this.mnuContextAddProduct.Text = "Add";
         this.mnuContextAddProduct.Click += new System.EventHandler(this.mnuContextAddProduct_Click);
         // 
         // mnuContextRemoveProduct
         // 
         this.mnuContextRemoveProduct.Index = 5;
         this.mnuContextRemoveProduct.Text = "Remove";
         this.mnuContextRemoveProduct.Click += new System.EventHandler(this.mnuContextRemoveProduct_Click);
         // 
         // imgTreeList
         // 
         this.imgTreeList.ImageSize = new System.Drawing.Size(16, 16);
         this.imgTreeList.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("imgTreeList.ImageStream")));
         this.imgTreeList.TransparentColor = System.Drawing.Color.Transparent;
         // 
         // btnAddCategory
         // 
         this.btnAddCategory.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
         this.btnAddCategory.Location = new System.Drawing.Point(8, 449);
         this.btnAddCategory.Name = "btnAddCategory";
         this.btnAddCategory.Size = new System.Drawing.Size(136, 24);
         this.btnAddCategory.TabIndex = 2;
         this.btnAddCategory.Text = "Add Category";
         this.btnAddCategory.Click += new System.EventHandler(this.btnAddCategory_Click);
         // 
         // btnAddProduct
         // 
         this.btnAddProduct.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
         this.btnAddProduct.Location = new System.Drawing.Point(8, 449);
         this.btnAddProduct.Name = "btnAddProduct";
         this.btnAddProduct.Size = new System.Drawing.Size(136, 24);
         this.btnAddProduct.TabIndex = 3;
         this.btnAddProduct.Text = "Add Parent Product";
         this.btnAddProduct.Click += new System.EventHandler(this.btnAddProduct_Click);
         // 
         // label1
         // 
         this.label1.Font = new System.Drawing.Font("Tahoma", 9F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
         this.label1.Location = new System.Drawing.Point(8, 8);
         this.label1.Name = "label1";
         this.label1.Size = new System.Drawing.Size(104, 16);
         this.label1.TabIndex = 4;
         this.label1.Text = "Category List";
         // 
         // lblAvailableItemsInCategory
         // 
         this.lblAvailableItemsInCategory.Font = new System.Drawing.Font("Tahoma", 9F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
         this.lblAvailableItemsInCategory.Location = new System.Drawing.Point(8, 8);
         this.lblAvailableItemsInCategory.Name = "lblAvailableItemsInCategory";
         this.lblAvailableItemsInCategory.Size = new System.Drawing.Size(384, 16);
         this.lblAvailableItemsInCategory.TabIndex = 5;
         this.lblAvailableItemsInCategory.Text = "Available Items in Category:";
         // 
         // pnlLeft
         // 
         this.pnlLeft.Controls.Add(this.ctlCategoryList);
         this.pnlLeft.Controls.Add(this.btnAddCategory);
         this.pnlLeft.Controls.Add(this.label1);
         this.pnlLeft.Dock = System.Windows.Forms.DockStyle.Left;
         this.pnlLeft.Location = new System.Drawing.Point(0, 0);
         this.pnlLeft.Name = "pnlLeft";
         this.pnlLeft.Size = new System.Drawing.Size(264, 481);
         this.pnlLeft.TabIndex = 6;
         // 
         // ctlCategoryList
         // 
         this.ctlCategoryList.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) 
            | System.Windows.Forms.AnchorStyles.Left) 
            | System.Windows.Forms.AnchorStyles.Right)));
         this.ctlCategoryList.BorderStyle = Infragistics.Win.UIElementBorderStyle.Inset;
         this.ctlCategoryList.ColumnSettings.RootColumnSet = ultraTreeColumnSet1;
         this.ctlCategoryList.ContextMenu = this.mnuTreeList;
         this.ctlCategoryList.HideSelection = false;
         this.ctlCategoryList.ImageList = this.imgTreeList;
         this.ctlCategoryList.Location = new System.Drawing.Point(8, 24);
         this.ctlCategoryList.Name = "ctlCategoryList";
         this.ctlCategoryList.Size = new System.Drawing.Size(256, 416);
         this.ctlCategoryList.TabIndex = 5;
         this.ctlCategoryList.Click += new System.EventHandler(this.ctlCategoryList_Click);
         this.ctlCategoryList.DoubleClick += new System.EventHandler(this.ctlCategoryList_DoubleClick);
         // 
         // mnuTreeList
         // 
         this.mnuTreeList.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
                                                                                    this.mnuModifyCategory,
                                                                                    this.menuItem15,
                                                                                    this.mnuAddCategory,
                                                                                    this.mnuRemoveCategory,
                                                                                    this.menuItem11,
                                                                                    this.mnuMoveUp,
                                                                                    this.mnuMoveDown,
                                                                                    this.mnuMoveLeft,
                                                                                    this.mnuMoveRight});
         this.mnuTreeList.Popup += new System.EventHandler(this.mnuTreeList_Popup);
         // 
         // mnuModifyCategory
         // 
         this.mnuModifyCategory.Index = 0;
         this.mnuModifyCategory.Text = "Modify";
         this.mnuModifyCategory.Click += new System.EventHandler(this.mnuModifyCategory_Click);
         // 
         // menuItem15
         // 
         this.menuItem15.Index = 1;
         this.menuItem15.Text = "-";
         // 
         // mnuAddCategory
         // 
         this.mnuAddCategory.Index = 2;
         this.mnuAddCategory.Text = "Add";
         this.mnuAddCategory.Click += new System.EventHandler(this.mnuAddCategory_Click);
         // 
         // mnuRemoveCategory
         // 
         this.mnuRemoveCategory.Index = 3;
         this.mnuRemoveCategory.Text = "Remove";
         this.mnuRemoveCategory.Click += new System.EventHandler(this.mnuRemoveCategory_Click);
         // 
         // menuItem11
         // 
         this.menuItem11.Index = 4;
         this.menuItem11.Text = "-";
         // 
         // mnuMoveUp
         // 
         this.mnuMoveUp.Index = 5;
         this.mnuMoveUp.Text = "Move Up";
         this.mnuMoveUp.Click += new System.EventHandler(this.mnuMoveUp_Click);
         // 
         // mnuMoveDown
         // 
         this.mnuMoveDown.Index = 6;
         this.mnuMoveDown.Text = "Move Down";
         this.mnuMoveDown.Click += new System.EventHandler(this.mnuMoveDown_Click);
         // 
         // mnuMoveLeft
         // 
         this.mnuMoveLeft.Index = 7;
         this.mnuMoveLeft.Text = "Move Left";
         this.mnuMoveLeft.Click += new System.EventHandler(this.mnuMoveLeft_Click);
         // 
         // mnuMoveRight
         // 
         this.mnuMoveRight.Index = 8;
         this.mnuMoveRight.Text = "Move Right";
         this.mnuMoveRight.Click += new System.EventHandler(this.mnuMoveRight_Click);
         // 
         // pnlRight
         // 
         this.pnlRight.Controls.Add(this.lblAvailableItemsInCategory);
         this.pnlRight.Controls.Add(this.btnAddProduct);
         this.pnlRight.Controls.Add(this.ctlProductList);
         this.pnlRight.Dock = System.Windows.Forms.DockStyle.Fill;
         this.pnlRight.Location = new System.Drawing.Point(264, 0);
         this.pnlRight.Name = "pnlRight";
         this.pnlRight.Size = new System.Drawing.Size(416, 481);
         this.pnlRight.TabIndex = 7;
         // 
         // splitter1
         // 
         this.splitter1.Location = new System.Drawing.Point(264, 0);
         this.splitter1.Name = "splitter1";
         this.splitter1.Size = new System.Drawing.Size(6, 481);
         this.splitter1.TabIndex = 8;
         this.splitter1.TabStop = false;
         // 
         // menuItem1
         // 
         this.menuItem1.Index = 6;
         this.menuItem1.Text = "-";
         // 
         // mnuMoveProductUp
         // 
         this.mnuMoveProductUp.Index = 7;
         this.mnuMoveProductUp.Text = "Move Up";
         this.mnuMoveProductUp.Click += new System.EventHandler(this.mnuMoveProductUp_Click);
         // 
         // mnuMoveProductDown
         // 
         this.mnuMoveProductDown.Index = 8;
         this.mnuMoveProductDown.Text = "Move Down";
         this.mnuMoveProductDown.Click += new System.EventHandler(this.mnuMoveProductDown_Click);
         // 
         // MainWindow
         // 
         this.AutoScaleBaseSize = new System.Drawing.Size(6, 15);
         this.ClientSize = new System.Drawing.Size(680, 481);
         this.Controls.Add(this.splitter1);
         this.Controls.Add(this.pnlRight);
         this.Controls.Add(this.pnlLeft);
         this.Font = new System.Drawing.Font("Tahoma", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
         this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
         this.Menu = this.mnuMainMenu;
         this.Name = "MainWindow";
         this.Text = "QuoteAdvantage Editor";
         this.Closing += new System.ComponentModel.CancelEventHandler(this.MainWindow_Closing);
         this.Load += new System.EventHandler(this.MainWindow_Load);
         this.pnlLeft.ResumeLayout(false);
         ((System.ComponentModel.ISupportInitialize)(this.ctlCategoryList)).EndInit();
         this.pnlRight.ResumeLayout(false);
         this.ResumeLayout(false);

      }
		#endregion

		/// <summary>
		/// The main entry point for the application.
		/// </summary>
		[STAThread]
		static void Main() 
		{
			Application.Run(new MainWindow());
		}


      private void ConnectToCrm()
      {
         MessageWindow  msgWin = new MessageWindow();

         try
         {
            Cursor oldCursor = Cursor.Current;
            Cursor.Current = Cursors.WaitCursor; 


            msgWin.Location = new Point(this.Location.X + 200, this.Location.Y + 200);
            msgWin.Show();
            msgWin.Update();
            eng.Connect(objSettings);
            msgWin.Close();
            Cursor.Current = oldCursor; 
         }
         catch (Exception ex)
         {
            throw ex;
         }
         finally
         {
            msgWin.Close();
         }
      }

      private void MainWindow_Load(object sender, System.EventArgs e)
      {
         Cursor oldCursor = Cursor.Current;
         Cursor.Current = Cursors.WaitCursor; 
         
         string strCrmError = "";

         this.Show();
         this.Update();
         Cursor.Current = Cursors.WaitCursor; 

         try
         {  
            objSettings.LoadSettings();
            ConnectToCrm();
         }
         catch(Exception ex)
         {
            strCrmError = "Unable to connect to Microsoft CRM\r\n\r\n" + ex.Message;
         } 

         Cursor.Current = oldCursor; 

         if (strCrmError != "")
         {
            MessageBox.Show(this, strCrmError, "QuoteAdvantage Editor");
            UpdateSettings();
         }
         else
         {
            QuickStartDlg  dlgQuickStart = new QuickStartDlg();
            
            dlgQuickStart.SettingsData = objSettings;

            if(dlgQuickStart.ShowDialog(this) == DialogResult.OK)
            {
               Update();
               strCategoryListFileName = dlgQuickStart.FolderName + @"\CategoryList.xml";
               bNeedSave = false;

               if (dlgQuickStart.FileOpenResult)
               {
                  LoadCategoryList();
               }
               else
               {
                  Cursor.Current = Cursors.WaitCursor; 
               
                  CreateCategoryList(strCategoryListFileName);
                  LoadCategoryList(); 
               
                  Cursor.Current = oldCursor;
               }
            }
         }

         EnableControls();
      }

      private void mnuFileExit_Click(object sender, System.EventArgs e)
      {
         this.Close();
      }

      private void mnuFileOpen_Click(object sender, System.EventArgs e)
      {           
         OpenFileDialog dlg = new OpenFileDialog();
         dlg.Title = "Open CategoryList.xml File";
         dlg.InitialDirectory = @"c:\";
         dlg.Filter = "CategoryList.xml (*.xml)|*.*";
         dlg.FilterIndex = 2;
         dlg.RestoreDirectory = true;
         
         if(dlg.ShowDialog() == DialogResult.OK)
         {
            Cursor oldCursor = Cursor.Current;
            Cursor.Current = Cursors.WaitCursor; 
            
            strCategoryListFileName = dlg.FileName;
            
            if (LoadCategoryList())
            {
               objSettings.strMRU_CategoryList = Path.GetDirectoryName(dlg.FileName);
               objSettings.SaveSettings();
            }
            else
            {
               // There was an error opening the file
               strCategoryListFileName = "";
            }
            
            Cursor.Current = oldCursor;
         } 

         EnableControls();
      }

      private void mnuHelpAbout_Click(object sender, System.EventArgs e)
      {
         AboutDlg dlg = new AboutDlg();

         dlg.ShowDialog();
      }


      private void btnAddCategory_Click(object sender, System.EventArgs e)
      {
         AddCategory();
      }

      private void AddCategory()
      {
         CategoryModifyDlg dlg = new CategoryModifyDlg();
         XmlNode  nodeParent = null;
         XmlDocument  objDocument = nodeCategoryListRoot.OwnerDocument;
         XmlNode  nodeSelected = null;

         if (ctlCategoryList.SelectedNodes.Count > 0)
         {
            nodeSelected = nodeSelected = (XmlNode)ctlCategoryList.SelectedNodes[0].DataKey;
            nodeParent = nodeSelected.ParentNode;
         }
         else
         {
            nodeParent = nodeCategoryListRoot;
            nodeSelected = null;
         }

         XmlNode  nodeNewCategory = objDocument.CreateElement("", "Category", "");
         XmlAttribute attrib = objDocument.CreateAttribute("", "name", "");
         attrib.Value = "Untitled";
         nodeNewCategory.Attributes.Append(attrib);

         attrib = objDocument.CreateAttribute("", "categoryId", "");  
         attrib.Value = "UNTITLED_CATEGORY";
         nodeNewCategory.Attributes.Append(attrib);
          
         if (nodeSelected == null)
         {
            nodeParent.AppendChild(nodeNewCategory);
         }
         else
         {
            nodeParent.InsertAfter(nodeNewCategory, nodeSelected); // Add as the next sibling
         }

         dlg.Engine = eng;
         dlg.CategoryNode = nodeNewCategory;
         dlg.ShowDialog(this);

         if (dlg.DialogResult == DialogResult.OK)
         {
            bNeedSave = true;
            RefreshCategoryList(); 

            if (ctlCategoryList.ActiveNode == null)
            {
               ctlCategoryList.ActiveNode = ctlCategoryList.Nodes[0];
               ctlCategoryList.ActiveNode.Selected = true;
            }
            else
            {
               ctlCategoryList.ActiveNode = ctlCategoryList.ActiveNode.GetSibling(NodePosition.Next);
               ctlCategoryList.ActiveNode.Selected = true;
            }

            RefreshProductList();
         }
         else
         {
            // We're not going to add it
            nodeParent.RemoveChild(nodeNewCategory);
         }
      }

      private void btnAddProduct_Click(object sender, System.EventArgs e)
      {
         AddProduct();
      }

      private void AddProduct()
      {
         ParentProductDlg dlg = new ParentProductDlg();
         
         XmlNode  nodeParent = (XmlNode)ctlCategoryList.SelectedNodes[0].DataKey;
         XmlNode  nodeNewProduct = nodeParent.OwnerDocument.CreateElement("", "Item", "");
         
         XmlAttribute attrib = nodeParent.OwnerDocument.CreateAttribute("", "productId", "");
         nodeNewProduct.Attributes.Append(attrib);
         nodeParent.AppendChild(nodeNewProduct);

         attrib = nodeParent.OwnerDocument.CreateAttribute("", "ruleFileName", "");
         nodeNewProduct.Attributes.Append(attrib);
         nodeParent.AppendChild(nodeNewProduct);
         
         attrib = nodeParent.OwnerDocument.CreateAttribute("", "allowDiscounting", "");
         attrib.Value = "true";
         nodeNewProduct.Attributes.Append(attrib);
         nodeParent.AppendChild(nodeNewProduct);
         
         dlg.Engine = eng;
         dlg.ProductNode = nodeNewProduct;
         dlg.ShowDialog(this);

         if (dlg.DialogResult == DialogResult.OK)
         {
            bNeedSave = true;
            RefreshProductList(); 
         }
         else
         {
            // We're not going to add it
            nodeParent.RemoveChild(nodeNewProduct);
         }
      }

      private void ModifyProduct()
      {
         ParentProductDlg dlg = new ParentProductDlg();
         
         XmlNode  node = (XmlNode)ctlProductList.SelectedItems[0].Tag;

         dlg.Engine = eng;
         dlg.ProductNode = node;
         dlg.ShowDialog(this);

         if (dlg.DialogResult == DialogResult.OK)
         {
            bNeedSave = true;
            RefreshProductList(); 
         }
      }

      private void MoveProductUp()
      {        
         int nPos = ctlProductList.SelectedItems[0].Index;
         XmlNode  node = (XmlNode)ctlProductList.SelectedItems[0].Tag;
         XmlNode nodeParent = node.ParentNode;
         XmlNode nodePrev = node.PreviousSibling;

         if (nodePrev != null)
         {
            nodeParent.RemoveChild(node);
            nodeParent.InsertBefore(node, nodePrev);
            RefreshProductList(); 
            ctlProductList.Items[nPos-1].Selected = true;
         }
      }

      private void MoveProductDown()
      {
         int nPos = ctlProductList.SelectedItems[0].Index;
         XmlNode  node = (XmlNode)ctlProductList.SelectedItems[0].Tag;
         XmlNode nodeParent = node.ParentNode;
         XmlNode nodeNext = node.NextSibling;

         if (nodeNext != null)
         {
            nodeParent.RemoveChild(node);
            nodeParent.InsertAfter(node, nodeNext);
            RefreshProductList(); 
            ctlProductList.Items[nPos+1].Selected = true;
         }
      }

      private void ModifyCategory()
      {
         CategoryModifyDlg dlg = new CategoryModifyDlg();
         
         XmlNode  node = (XmlNode)ctlCategoryList.SelectedNodes[0].DataKey;

         dlg.Engine = eng;
         dlg.CategoryNode = node;
         dlg.ShowDialog(this);

         if (dlg.DialogResult == DialogResult.OK)
         {
            bNeedSave = true;
            RefreshCategoryList(); 
         }
      }

      // Load the category list from the XML file     
      private bool LoadCategoryList()
      {
         Cursor oldCursor = Cursor.Current;
         Cursor.Current = Cursors.WaitCursor; 
         
         bool bResult = true;

         try
         {           
            nodeCategoryListRoot = null;
            ctlCategoryList.Nodes.Clear();
            ctlProductList.Items.Clear();
            nodeCategoryListRoot = eng.LoadProductCategoryList(strCategoryListFileName);
            RefreshCategoryList();
         }
         catch (Exception ex)
         {
            MessageBox.Show(this, "Error loading CategoryList file: " + ex.Message, "QuoteAdvantage Editor");
            bResult = false;
         }

         Cursor.Current = oldCursor; 

         return bResult;
      }


      // Refresh the category list tree from the copy in memory
      private void RefreshCategoryList()
      {
         Cursor oldCursor = Cursor.Current;
         Cursor.Current = Cursors.WaitCursor; 
         
         string strSelectedKey = "";

         if (ctlCategoryList.SelectedNodes.Count > 0)
         {
            strSelectedKey = ctlCategoryList.SelectedNodes[0].Key;
         }
         
         ctlCategoryList.Nodes.Clear();
         ctlProductList.Items.Clear();

         if (nodeCategoryListRoot == null)
         {
            throw new ApplicationException("The <CategoryList> node was not found in the CategoryList.xml file.");
         }
         else
         {
            UltraTreeNode        nodeRoot = new UltraTreeNode();

            LoadChildItems(nodeRoot, nodeCategoryListRoot);     
            ctlCategoryList.Nodes.Clear();

            foreach (UltraTreeNode item in nodeRoot.Nodes)
            {
               ctlCategoryList.Nodes.Add(item);
            }
         }

         if (ctlCategoryList.Nodes.Count > 0)
         {
            ctlCategoryList.Nodes[0].Selected = true;
            ctlCategoryList.ActiveNode = ctlCategoryList.Nodes[0];
            RefreshProductList();
         }

         if (strSelectedKey != "")
         {
            UltraTreeNode node = ctlCategoryList.GetNodeByKey(strSelectedKey);

            if (node != null)
            {
               node.BringIntoView();
               ctlCategoryList.ActiveNode = node;    
               node.Selected = true;
            }
         }

         EnableControls();
         Cursor.Current = oldCursor; 
      }

      private void LoadChildItems(UltraTreeNode treeParentNode, XmlNode xmlParentNode)
      {
         string strNodeName = "";
         string strKeyValue = "";
                     
         try
         {
            foreach (XmlNode nodeChild in xmlParentNode.ChildNodes)
            {
               if (nodeChild.Name == "Category")
               {
                  strNodeName = nodeChild.Attributes["name"].Value;
                  XmlAttribute   attrib = nodeChild.Attributes["categoryId"];

                  // categoryId attribute is optional
                  if (attrib == null)
                     strKeyValue = "";
                  else
                     strKeyValue = attrib.Value;                       
                  
                  UltraTreeNode  nodeItem = new UltraTreeNode(strKeyValue, strNodeName);
                  nodeItem.DataKey = nodeChild;
                  nodeItem.LeftImages.Add(0);
                  LoadChildItems(nodeItem, nodeChild);
                  treeParentNode.Nodes.Add(nodeItem);
               }
            }
         }
         catch (Exception ex)
         {
            string strMessage = "There was an error processing the category tree item named: " + strNodeName;
            throw new ApplicationException(strMessage, ex);
         }
      }

      private void ctlCategoryList_Click(object sender, System.EventArgs e)
      {
         RefreshProductList();
      }

      private void RefreshProductList()
      {
         Cursor oldCursor = Cursor.Current;
         Cursor.Current = Cursors.WaitCursor; 
         
         ctlProductList.BeginUpdate();
         string strCategoryName = "";
         ctlProductList.Items.Clear();
  
         if (ctlCategoryList.SelectedNodes.Count > 0)
         {
            UltraTreeNode  nodeSelected = ctlCategoryList.SelectedNodes[0];
            XmlNode        objCategoryTreeNode = (XmlNode)nodeSelected.DataKey;

            strCategoryName = nodeSelected.Text;

            foreach (XmlNode nodeItem in objCategoryTreeNode.ChildNodes)
            {
               if (nodeItem.Name == "Item")
               {
                  string strProductId = nodeItem.Attributes["productId"].Value;
                  Product  objProduct = eng.LoadProductFromProductNumber(strProductId); 
                  ListViewItem   objItem = null;

                  if (objProduct == null)
                  {
                     objItem = new ListViewItem("Product Description Not Available", 1);
                     objItem.Tag = nodeItem;
                     objItem.SubItems.Add(strProductId);
                  }
                  else
                  {
                     objItem = new ListViewItem(objProduct.Name, 1);
                     objItem.Tag = nodeItem;
                     objItem.SubItems.Add(objProduct.ProductNumber);
                  }

                  ctlProductList.Items.Add(objItem); 
               }
            }
         }
         
         lblAvailableItemsInCategory.Text = "Available Items in Category: " + strCategoryName;
         ctlProductList.EndUpdate();

         Cursor.Current = oldCursor; 
      }

      private void ctlProductList_DoubleClick(object sender, System.EventArgs e)
      {
         if (!bWorking)
         {
            bWorking = true; 
            ModifyChildProducts();
            bWorking = false;
         }
      }

      private void mnuFileSettings_Click(object sender, System.EventArgs e)
      {
         UpdateSettings();
      }

      private void UpdateSettings()
      {
         SettingsDlg dlg = new SettingsDlg();

         dlg.SettingsData = objSettings;
         dlg.ShowDialog(this);

         if (dlg.DialogResult == DialogResult.OK)
         {
            try
            {
               ConnectToCrm();
               MessageBox.Show(this, "Successfully connected to Microsoft CRM", "QuoteAdvantage Editor");

               if (strCategoryListFileName == "")
               {
                  QuickStartDlg  dlgQuickStart = new QuickStartDlg();
   
                  dlgQuickStart.SettingsData = objSettings;
                  dlgQuickStart.ShowDialog(this);

                  if (dlgQuickStart.DialogResult == DialogResult.OK)
                  {
                     strCategoryListFileName = dlgQuickStart.FolderName + @"\CategoryList.xml";;
                  }
               }

               this.Update();
               LoadCategoryList();
            }
            catch(Exception ex)
            {
               MessageBox.Show(this, "Error connecting to Microsoft CRM\r\n\r\n" + ex.Message, "QuoteAdvantage Editor");
               ctlCategoryList.Nodes.Clear();
               nodeCategoryListRoot = null;
               ctlProductList.Items.Clear();
            }
         }

         EnableControls();
      }
   

      private void ModifyChildProducts()
      {
         Cursor oldCursor = Cursor.Current;
         Cursor.Current = Cursors.WaitCursor; 

         XmlNode              objSelectedNode = (XmlNode)ctlProductList.SelectedItems[0].Tag;
         string               strProductId = objSelectedNode.Attributes["productId"].Value;
         Product              objParentProduct = eng.LoadProductFromProductNumber(strProductId);
         
         if (objParentProduct == null)
         {
            MessageBox.Show(this, "This parent product could not be loaded from the Microsoft CRM Product Catalog.", "QuoteAdvantage Editor");
         }
         else
         {
            ProductCustomizeDlg  dlg = new ProductCustomizeDlg();
            string               strRuleFileName = "";
            
            if (objSelectedNode.Attributes["ruleFileName"] != null)
            {
               strRuleFileName = objSelectedNode.Attributes["ruleFileName"].Value;
            }

            if (strRuleFileName == "")
            {
               MessageBox.Show(this, "This parent product does not have a rule file name \r\nspecified for managing child products.", "Unable to Load Child Products");
            }
            else
            {
               FileInfo info = new FileInfo(strCategoryListFileName);
               string strRuleFileNameFullPath = info.DirectoryName + "\\" + strRuleFileName;
            
               if (!File.Exists(strRuleFileNameFullPath))
               {
                  // Create a new rule file
                  CreateNewRuleFile(strRuleFileNameFullPath);
               }

               if (!File.Exists(strRuleFileNameFullPath))
               {
                  MessageBox.Show(this, strRuleFileNameFullPath + " could not be found.", "QuoteAdvantage Editor");
               }
               else
               {
                  dlg.RuleFileName = strRuleFileNameFullPath;
                  dlg.ParentProduct = objParentProduct;
                  dlg.Engine = eng;

                  Cursor.Current = oldCursor;

                  try
                  {
                     dlg.ShowDialog(this);

                     if (dlg.DialogResult == DialogResult.OK)
                     {
                     }
                  }
                  catch (Exception ex)
                  {
                     MessageBox.Show(this, ex.Message, "QuoteAdvantage Editor");
                  }
               }
            }
         } // end if - Product is available
      }               

      private void mnuProductList_Popup(object sender, System.EventArgs e)
      {
         EnableControls();
      }

      private void mnuContextModifyProduct_Click(object sender, System.EventArgs e)
      {
         ModifyProduct();
      }

      private void mnuContextChildProducts_Click(object sender, System.EventArgs e)
      {
         ModifyChildProducts();
      }

      private void mnuTreeList_Popup(object sender, System.EventArgs e)
      {
         EnableControls();
      }

      private void mnuContextAddProduct_Click(object sender, System.EventArgs e)
      {
         AddProduct();
      }

      private void MainWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e)
      {
         if (bNeedSave)
         {
            DialogResult result = MessageBox.Show(this, "Would you like to save your changes?", "QuoteAdvantage Editor", MessageBoxButtons.YesNoCancel);
 
            switch (result)
            {
               case DialogResult.Cancel:
                  e.Cancel = true;
                  break;

               case DialogResult.Yes:
                  Cursor oldCursor = Cursor.Current;
                  Cursor.Current = Cursors.WaitCursor; 
         
                  if (SaveChanges() == false)
                  {
                     e.Cancel = true;  // Abort the close
                  }
         
                  Cursor.Current = oldCursor; 
                  break;
            }
         }
      }

      private void mnuAddCategory_Click(object sender, System.EventArgs e)
      {
         AddCategory();
      }

      private void mnuModifyCategory_Click(object sender, System.EventArgs e)
      {
         ModifyCategory();
      }

      private void mnuFileNew_Click(object sender, System.EventArgs e)
      {
         string strFolderName;

         DirBrowser  dlg = new DirBrowser();

         dlg.Description = "Please select a location for the new CategoryList.xml file:";
         dlg.ShowDialog(); 
         strFolderName = dlg.ReturnPath;

         if (strFolderName != String.Empty)
         {
            if (File.Exists(strFolderName + @"\CategoryList.xml"))
            {
               MessageBox.Show(this, "A CategoryList.xml file already exists in that folder. Please select a different location.");
            }
            else
            {
               Cursor oldCursor = Cursor.Current;
               Cursor.Current = Cursors.WaitCursor; 
               
               CreateCategoryList(strFolderName + @"\CategoryList.xml");
               strCategoryListFileName = strFolderName + @"\CategoryList.xml";
               LoadCategoryList(); 
               
               Cursor.Current = oldCursor;
            }
         }
      }

      private void CreateCategoryList(string strFilePath)
      {
         TextWriter  objFile = new StreamWriter(strFilePath);

         objFile.WriteLine(@"<?xml version=""1.0"" encoding=""utf-8"" ?>");
         objFile.WriteLine(@"<ConfigurationData>");
         objFile.WriteLine(@"    <CategoryList name=""Products"">");
         objFile.WriteLine(@"       <Category name=""Untitled Category 1"" categoryId=""UNTITLED_1"">");
         objFile.WriteLine(@"          <Category name=""Untitled Category 3"" categoryId=""UNTITLED_3"">");
         objFile.WriteLine(@"          </Category>");
         objFile.WriteLine(@"       </Category>");
         objFile.WriteLine(@"       <Category name=""Untitled Category 2"" categoryId=""UNTITLED_2"">");
         objFile.WriteLine(@"       </Category>");
         objFile.WriteLine(@"   </CategoryList>");
         objFile.WriteLine(@"</ConfigurationData>");
         objFile.Close();
         bNeedSave = true;
      }

      private void mnuFileSave_Click(object sender, System.EventArgs e)
      {
         Cursor oldCursor = Cursor.Current;
         Cursor.Current = Cursors.WaitCursor; 
         
         SaveChanges();
         
         Cursor.Current = oldCursor;
      }

      private bool SaveChanges()
      {
         bool bResult = false;

         FileInfo objInfo = new FileInfo(strCategoryListFileName);
         
         if ((objInfo.Attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)
         {
            MessageBox.Show(this, "Unable to save. CategoryList.xml file is read-only.", "QuoteAdvantage Editor");
         }
         else
         {
            nodeCategoryListRoot.OwnerDocument.Save(strCategoryListFileName);
            bResult = true;
            bNeedSave = false;
         }
         
         return bResult;
      }

      private void CreateNewRuleFile(string strRuleFileNameFullPath)
      {
         TextWriter  objFile = new StreamWriter(strRuleFileNameFullPath);

         objFile.WriteLine(@"<?xml version=""1.0"" encoding=""utf-8"" ?>");
         objFile.WriteLine(@"<ConfigurationData>");
         objFile.WriteLine(@"   <Category name=""Untitled Category"" categoryId=""UNTITLED_CATEGORY"">"); 
         objFile.WriteLine(@"   </Category>");
         objFile.WriteLine(@"</ConfigurationData>");
         objFile.Close();
      }

      private void mnuEditCategoryAdd_Click(object sender, System.EventArgs e)
      {
         AddCategory();
      }

      private void mnuMoveUp_Click(object sender, System.EventArgs e)
      {
         MoveCategoryUp();
      }

      private void mnuMoveDown_Click(object sender, System.EventArgs e)
      {
         MoveCategoryDown();
      }

      private void mnuMoveLeft_Click(object sender, System.EventArgs e)
      {
         MoveCategoryLeft();
      }

      private void mnuMoveRight_Click(object sender, System.EventArgs e)
      {
         MoveCategoryRight();
      }

      private void MoveCategoryUp()
      {
         if (ctlCategoryList.SelectedNodes.Count > 0)
         {
            UltraTreeNode  guiNode = ctlCategoryList.SelectedNodes[0];
            XmlNode  node = (XmlNode)guiNode.DataKey;
            XmlNode  nodePrev = node.PreviousSibling;
            XmlNode  nodeComment = null;
            TreeNodesCollection  objSiblingGuiNodeCollection;
            XmlNode  nodeParent = null;

            if (guiNode.Parent == null)
            {  
               // We're moving a root level category
               nodeParent = node.OwnerDocument.SelectSingleNode("//CategoryList");
               objSiblingGuiNodeCollection = ctlCategoryList.Nodes;
            }
            else
            {
               // We're moving a regular node
               nodeParent = node.ParentNode;
               objSiblingGuiNodeCollection = guiNode.ParentNodesCollection;
            }                 
               
            if (nodePrev.NodeType == XmlNodeType.Comment)
            {
               nodeComment = nodePrev;
               nodePrev = nodePrev.PreviousSibling;
            }

            if (nodePrev != null)
            {
               // Move the data node
               XmlNode child = nodeParent.RemoveChild(node);

               if (nodeComment != null)
               {
                  XmlNode childComment = nodeParent.RemoveChild(nodeComment);

                  nodeParent.InsertBefore(child, nodePrev);

                  if (nodeComment != null)
                     nodeParent.InsertBefore(childComment, child);
               }
               else
               {
                  nodeParent.InsertBefore(child, nodePrev);
               }        

               // Move the GUI node
               int      nPos = guiNode.Index;

               objSiblingGuiNodeCollection.RemoveAt(nPos);
               objSiblingGuiNodeCollection.Insert(nPos-1, guiNode);
               ctlCategoryList.ActiveNode = guiNode;
               bNeedSave = true;
            }
         }         
      }

      private void MoveCategoryDown()
      {
         if (ctlCategoryList.SelectedNodes.Count > 0)
         {
            UltraTreeNode  guiNode = ctlCategoryList.SelectedNodes[0];
            XmlNode  node = (XmlNode)guiNode.DataKey;
            XmlNode  nodeNext = node.NextSibling;
            XmlNode  nodeComment = null;
            TreeNodesCollection  objSiblingGuiNodeCollection;
            XmlNode  nodeParent = null;

            if (guiNode.Parent == null)
            {  
               // We're moving a root level category
               nodeParent = node.OwnerDocument.SelectSingleNode("//CategoryList");
               objSiblingGuiNodeCollection = ctlCategoryList.Nodes;
            }
            else
            {
               // We're moving a regular node
               nodeParent = node.ParentNode;
               objSiblingGuiNodeCollection = guiNode.ParentNodesCollection;
            }                 
               
            if (nodeNext.NodeType == XmlNodeType.Comment)
            {
               nodeComment = nodeNext;
               nodeNext = nodeNext.NextSibling;
            }

            if (nodeNext != null)
            {
               // Move the data node
               XmlNode child = nodeParent.RemoveChild(node);

               if (nodeComment != null)
               {
                  XmlNode childComment = nodeParent.RemoveChild(nodeComment);

                  nodeParent.InsertAfter(child, nodeNext);

                  if (nodeComment != null)
                     nodeParent.InsertAfter(childComment, child);
               }
               else
               {
                  nodeParent.InsertAfter(child, nodeNext);
               }        

               // Move the GUI node
               int      nPos = guiNode.Index;

               objSiblingGuiNodeCollection.RemoveAt(nPos);
               objSiblingGuiNodeCollection.Insert(nPos+1, guiNode);
               ctlCategoryList.ActiveNode = guiNode;
               bNeedSave = true;
            }
         }         
      }

      // Move a node so that it becomes the next sibling that is just after its parent node
      private void MoveCategoryLeft()
      {
         if (ctlCategoryList.SelectedNodes.Count > 0)
         {
            UltraTreeNode  guiNode = ctlCategoryList.SelectedNodes[0];
            XmlNode  node = (XmlNode)guiNode.DataKey;
            XmlNode  nodeNext = node.NextSibling;
            XmlNode  nodeComment = null;
            XmlNode  nodeParent = null;

            if (guiNode.Parent == null)
            {  
               // Do not allow this operation on a root level category
            }
            else
            {
               // We're moving a regular node
               nodeParent = node.ParentNode;
            }                 
             
            if (nodeNext != null)
            {
               if (nodeNext.NodeType == XmlNodeType.Comment)
               {
                  nodeComment = nodeNext;
                  nodeNext = nodeNext.NextSibling;
               }
            }

            if (nodeParent != null)
            {
               // Move the data node
               XmlNode child = nodeParent.RemoveChild(node);

               if (nodeComment != null)
               {
                  XmlNode childComment = nodeParent.RemoveChild(nodeComment);

                  nodeParent.ParentNode.InsertAfter(child, nodeParent);

                  if (nodeComment != null)
                     nodeParent.ParentNode.InsertAfter(childComment, child);
               }
               else
               {
                  nodeParent.ParentNode.InsertAfter(child, nodeParent);
               }        

               // Move the GUI node
               guiNode.Reposition(guiNode.Parent, NodePosition.Next);
               ctlCategoryList.ActiveNode = guiNode;
               guiNode.Selected = true;           
               guiNode.BringIntoView();
               bNeedSave = true;
            }
         }         
      }


      // Move a node so that it will become its previous sibling's first child
      private void MoveCategoryRight()
      {
         if (ctlCategoryList.SelectedNodes.Count > 0)
         {
            UltraTreeNode  guiNode = ctlCategoryList.SelectedNodes[0];
            TreeNodesCollection  objSiblingGuiNodeCollection;
            XmlNode  node = (XmlNode)guiNode.DataKey;
            XmlNode  nodePrev = node.PreviousSibling;
            XmlNode  nodeComment = null;
            XmlNode  nodeParent = null;

            if (nodePrev != null)
            {
               if (guiNode.Parent == null)
               {  
                  // We're moving a root level category
                  nodeParent = node.OwnerDocument.SelectSingleNode("//CategoryList");
                  objSiblingGuiNodeCollection = ctlCategoryList.Nodes;
               }
               else
               {
                  // We're moving a regular node
                  nodeParent = node.ParentNode;
                  objSiblingGuiNodeCollection = guiNode.ParentNodesCollection;
               }                 
               
               if (nodePrev.NodeType == XmlNodeType.Comment)
               {
                  nodeComment = nodePrev;
                  nodePrev = nodePrev.NextSibling;
               }

               if (nodePrev != null)
               {
                  // Move the data node
                  XmlNode child = nodeParent.RemoveChild(node);

                  if (nodeComment != null)
                  {
                     XmlNode childComment = nodeParent.RemoveChild(nodeComment);

                     nodePrev.InsertBefore(child, nodePrev.FirstChild);

                     if (nodeComment != null)
                        nodePrev.InsertAfter(childComment, child);
                  }
                  else
                  {
                     nodePrev.InsertBefore(child, nodePrev.FirstChild);
                  }        

                  // Move the GUI node
                  int      nPos = guiNode.Index;
                  UltraTreeNode objPrevSibling = guiNode.GetSibling(NodePosition.Previous);

                  guiNode.ParentNodesCollection.Remove(guiNode);
                  objPrevSibling.Nodes.Insert(0, guiNode);
                  ctlCategoryList.ActiveNode = guiNode;
                  guiNode.Selected = true;
                  guiNode.BringIntoView();
                  bNeedSave = true;
               }
            }    
         }
      }

      private void EnableControls()
      {
         bool bAllowMoveDown = false;
         bool bAllowMoveUp = false;
         bool bAllowMoveRight = false;
         bool bAllowMoveLeft = false;
         bool bAllowRemoveCategory = false;
         bool bAllowModifyCategory = false;
         bool bAllowModifyProduct = false;
         bool bAllowAddProduct = false;
         bool bAllowAddCategory = false;
         bool bAllowFileOpen = false;
         bool bAllowProductMoveUp = false;
         bool bAllowProductMoveDown = false;

         if (eng.IsConnected())
         {
            if (strCategoryListFileName != "")
               bAllowAddCategory = true;

            bAllowFileOpen = true;
         }

         if (ctlCategoryList.SelectedNodes.Count > 0)
         {
            UltraTreeNode  guiNode = ctlCategoryList.SelectedNodes[0];

            bAllowRemoveCategory = true;
            bAllowModifyCategory = true;
            bAllowAddProduct = true;

            if (guiNode.GetSibling(NodePosition.Next) != null)
            {
               bAllowMoveDown = true;
            }

            if (guiNode.GetSibling(NodePosition.Previous) != null)
            {
               bAllowMoveUp = true;
               bAllowMoveRight = true;
            }

            if (guiNode.Parent != null)
               bAllowMoveLeft = true;
         }

         if (ctlProductList.SelectedItems.Count > 0)
         {
            bAllowModifyProduct = true;
         }

         if (ctlProductList.Items.Count > 1)
         {
            if (ctlProductList.SelectedItems.Count > 0)
            {
               if (ctlProductList.SelectedItems[0].Index > 0)
                  bAllowProductMoveUp = true;

               if (ctlProductList.SelectedItems[0].Index < ctlProductList.Items.Count-1)
                  bAllowProductMoveDown = true;
            }
         }

         mnuFileNew.Enabled = bAllowFileOpen;
         mnuFileOpen.Enabled = bAllowFileOpen;
         mnuFileSave.Enabled = bAllowAddCategory;

         mnuMoveUp.Enabled = bAllowMoveUp;
         mnuMoveUp2.Enabled = bAllowMoveUp;

         mnuMoveDown.Enabled = bAllowMoveDown;
         mnuMoveDown2.Enabled = bAllowMoveDown;

         mnuMoveRight.Enabled = bAllowMoveRight;
         mnuMoveRight2.Enabled = bAllowMoveRight;

         mnuMoveLeft.Enabled = bAllowMoveLeft;
         mnuMoveLeft2.Enabled = bAllowMoveLeft;  

         mnuEditCategoryAdd.Enabled = bAllowAddCategory;
         mnuRemoveCategory.Enabled = bAllowRemoveCategory;
         mnuEditCategoryRemove.Enabled = bAllowRemoveCategory;

         mnuEditCategoryModify.Enabled = bAllowModifyCategory;
         mnuModifyCategory.Enabled = bAllowModifyCategory;

         mnuContextRemoveProduct.Enabled = bAllowModifyProduct;
         mnuContextModifyProduct.Enabled = bAllowModifyProduct;
         mnuContextChildProducts.Enabled = bAllowModifyProduct;
         mnuContextLinkedItems.Enabled = bAllowModifyProduct;

         mnuEditParentProductRemove.Enabled = bAllowModifyProduct;
         mnuEditParentProductModify.Enabled = bAllowModifyProduct;
         mnuEditParentProductChildProducts.Enabled = bAllowModifyProduct;
         mnuEditParentProductLinkedItems.Enabled = bAllowModifyProduct;
 
         mnuEditParentProductAdd.Enabled = bAllowAddProduct;
         mnuContextAddProduct.Enabled = bAllowAddProduct;
         btnAddCategory.Enabled = bAllowAddCategory;
         btnAddProduct.Enabled = bAllowAddProduct;

         mnuMoveProductUp.Enabled = bAllowProductMoveUp;
         mnuMoveProductDown.Enabled = bAllowProductMoveDown;
      }

      private void mnuEditCategoryModify_Click(object sender, System.EventArgs e)
      {
         ModifyCategory();
      }


      private void RemoveCategory()
      {
         if (ctlCategoryList.SelectedNodes.Count > 0)
         {
            UltraTreeNode  objGuiNode = ctlCategoryList.SelectedNodes[0];
            XmlNode  nodeSelected = (XmlNode)objGuiNode.DataKey;
            
            nodeSelected.ParentNode.RemoveChild(nodeSelected);

            if (objGuiNode.Parent != null)
            {
               UltraTreeNode  parentNode = ctlCategoryList.SelectedNodes[0].Parent;

               parentNode.Selected = true;
               ctlCategoryList.ActiveNode = parentNode;    
            }

            RefreshCategoryList();
            bNeedSave = true;
         }
      }

      private void mnuEditCategoryRemove_Click(object sender, System.EventArgs e)
      {
         RemoveCategory();
      }

      private void mnuRemoveCategory_Click(object sender, System.EventArgs e)
      {
         RemoveCategory();
      }

      private void mnuEditCategory_Popup(object sender, System.EventArgs e)
      {
         EnableControls();
      }

      private void mnuEditParentProduct_Popup(object sender, System.EventArgs e)
      {
         EnableControls();
      }

      private void mnuEditParentProductRemove_Click(object sender, System.EventArgs e)
      {
         RemoveProduct();
      }

      private void mnuContextRemoveProduct_Click(object sender, System.EventArgs e)
      {
         RemoveProduct();
      }

      private void RemoveProduct()
      {
         Cursor oldCursor = Cursor.Current;
         Cursor.Current = Cursors.WaitCursor; 

         XmlNode  node = (XmlNode)ctlProductList.SelectedItems[0].Tag;

         node.ParentNode.RemoveChild(node);
         bNeedSave = true;
         RefreshProductList(); 
         Cursor.Current = oldCursor; 
      }

      private void mnuHelpTopics_Click(object sender, System.EventArgs e)
      {
         Process.Start("User Guide.pdf"); 
      }

      private void ctlCategoryList_DoubleClick(object sender, System.EventArgs e)
      {
         // In some circumstances, perform a Modify in response to a double-click
         UltraTreeNode  objSelectedNode = ctlCategoryList.ActiveNode;

         if ((objSelectedNode.Nodes.Count > 0) && objSelectedNode.Expanded)
         {
            ModifyCategory();   
         }
         else if (objSelectedNode.Nodes.Count == 0)
         {
            ModifyCategory();   
         }
      }

      private void mnuLinkedItems_Click(object sender, System.EventArgs e)
      {
         ModifyLinkedItems();
      }

      private void ModifyLinkedItems()
      {
         XmlNode  node = (XmlNode)ctlProductList.SelectedItems[0].Tag;
         LinkedItemListDlg dlg = new LinkedItemListDlg();

         dlg.InputItemNode = node;
         dlg.Engine = eng;
         dlg.ShowDialog();

         if (dlg.DialogResult == DialogResult.OK)
         {

         }
      }

      private void mnuEditParentProductLinkedItems_Click(object sender, System.EventArgs e)
      {
         ModifyLinkedItems();
      }

      private void mnuEditParentProductChildProducts_Click(object sender, System.EventArgs e)
      {
         ModifyChildProducts();
      }

      private void mnuEditParentProductModify_Click(object sender, System.EventArgs e)
      {
         ModifyProduct();
      }

      private void mnuEditParentProductAdd_Click(object sender, System.EventArgs e)
      {
          AddProduct();
      }

      private void mnuMoveProductUp_Click(object sender, System.EventArgs e)
      {
         MoveProductUp();
      }

      private void mnuMoveProductDown_Click(object sender, System.EventArgs e)
      {
         MoveProductDown();
      }
 

	}  // end class
}
